package rtc.core.net;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2018/2/23.
 */

public class MsgBody {
    public static final int VERSION = 0;
    public static final int CMD_RPC = 0;
    public static final int FLAG_NONE = 0;

    public final int ver;
    public final int cmd;
    public final int appid;
    public final int flag;
    public final String fn;
    public final int cb;
    public final JSONObject arg;

    public MsgBody(int appid, String fn, int cb, JSONObject arg){
        this(VERSION,CMD_RPC,appid,FLAG_NONE,fn,cb,arg);
    }

    public MsgBody(int ver, int cmd, int appid, int flag, String fn, int cb, JSONObject arg) {
        this.ver = ver;
        this.cmd = cmd;
        this.appid = appid;
        this.flag = flag;
        this.fn = fn;
        this.cb = cb;
        this.arg = arg;
    }

    public MsgBody(byte[] bytes) throws Exception{
        JSONObject msg = new JSONObject(new String(bytes));
        this.ver = msg.optInt("ver",0);
        this.cmd = msg.optInt("cmd",0);
        this.appid = msg.optInt("appid",0);
        this.flag = msg.optInt("flag",0);
        JSONObject data = msg.getJSONObject("data");
        this.fn = data.optString("fn");
        this.cb = data.optInt("cb");
        this.arg = data.getJSONObject("arg");
    }

    public byte[] pack(){
        JSONObject msg = new JSONObject();
        try {
            msg.put("ver",ver);
            msg.put("cmd",cmd);
            msg.put("appid",appid);
            msg.put("flag",flag);
            JSONObject data = new JSONObject();
            data.put("fn",fn);
            data.put("cb",cb);
            data.put("arg",arg);
            msg.put("data",data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return msg.toString().getBytes();
    }

    @Override
    public String toString() {
        return "MsgBody{" +
                "ver=" + ver +
                ", cmd=" + cmd +
                ", appid=" + appid +
                ", flag=" + flag +
                ", fn='" + fn + '\'' +
                ", cb=" + cb +
                ", arg=" + String.valueOf(arg) +
                '}';
    }
}
